/*
 * @(#)EmailRuleMessageInfo.java 
 * Copyright (c) 2006 DCIVision Ltd All rights reserved.
 * 
 *  This software is the confidential and proprietary information of DCIVision Ltd 
 *  ("Confidential Information"). You * shall not disclose such Confidential
 *   Information and shall use it only in accordance with the terms of the 
 *   license agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.alert.core;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import com.dcivision.dms.core.EmailRuleEngineHelper;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.Utility;
import com.dcivision.rules.action.NotifyEmailArchiveAction;
import com.dcivision.rules.core.RuleManager;

/**
 * <p>
 * Class Name: EmailRuleMessageInfo
 * </p>
 * 
 * @author Greatwall shao
 * @company DCIVision Limited
 * @creation date 2006-11-8
 */
public class EmailRuleMessageInfo extends AbstractMessageInfo {

  public EmailRuleMessageInfo() {
    
  }

  protected void setOtherInfo() throws ApplicationException {
    // from|to,cc|subject|ruleType|ruleName|ruleDesc|ruleKBFileName

    String[] emailInfo = makeEmailRuleInfo();

    makeEmailInfo(emailInfo);

    makeRuleInfo(emailInfo);
  }
  /**
   * @param emailInfo
   */
  private void makeRuleInfo(String[] emailInfo) { 
    this.messageInfoBean.setRuleType(replaceEspecialChar(emailInfo[3]));
    this.messageInfoBean.setRuleName(replaceEspecialChar(emailInfo[4]));
    this.messageInfoBean.setRuleDesc( makeRuleDesc(replaceEspecialChar(emailInfo[5])));
   /* List conditions = new ArrayList();
    List matchValues = new ArrayList();
    List rulenameList = new ArrayList();
    
    String[] ruleNames = replaceEspecialChar(emailInfo[5]).split(",");
    String[] conditionNames = replaceEspecialChar(emailInfo[7]).split(",");
    String[] conditionLables=getConditionName(replaceEspecialChar(emailInfo[7]));
    String[] conditionPredicates=replaceEspecialChar(emailInfo[8]).split(",");
    String[] conditionValues=replaceEspecialChar(emailInfo[9]).split(",");
    for(int i =0;i<ruleNames.length;i++){
      rulenameList.add(ruleNames[i]);
      conditions.add("\""+conditionLables[i]+"\" "+conditionPredicates[i]+" \""+replacespecialChar(conditionValues[i])+"\"");
      matchValues.add("\""+conditionLables[i]+"\" : \""+getEmailValue(conditionNames[i])+"\"");
    }
    this.messageInfoBean.setConditions(conditions);
    this.messageInfoBean.setMatchValues(matchValues);
    this.messageInfoBean.setRulenameList(rulenameList);
    makeRuleAction(replaceEspecialChar(emailInfo[10]));*/
  }

  /**
   * @param emailInfo
   * @return
   */
  private String makeRuleDesc(String ruledesc) {
    String str = "";
    if(!Utility.isEmpty(ruledesc)){
      str = ruledesc;
      if(ruledesc.indexOf("&nbsp;")!=-1){ 
        str = ruledesc.replaceAll("&nbsp;", " ");
      }
      if(str.indexOf("<br>")!=-1){ 
        str = str.replaceAll("<br>", "\n");
      }
    }
    return str;
  }
  

  /**
   * @param emailInfo
   */
  private void makeEmailInfo(String[] emailInfo) {

    this.messageInfoBean.setEmailFrom(replaceEspecialChar(emailInfo[0]));
    this.messageInfoBean.setEmailTo(replaceEspecialChar(emailInfo[1]));
    this.messageInfoBean.setEmailSubject(replaceEspecialChar(emailInfo[2]));
//    this.messageInfoBean.setEmailID(replaceEspecialChar(emailInfo[3]));
//    this.messageInfoBean.setEmailcc(replaceEspecialChar(emailInfo[11]));
//    this.messageInfoBean.setAttatchmentNum(emailInfo[12]);
    this.messageInfoBean.setMatchEmail(
        MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),
            "home.message.emailRule_notification.matched_email", replaceEspecialChar(emailInfo[2]), 
            replaceEspecialChar(emailInfo[0]),replaceEspecialChar(emailInfo[1])));
  }
  

  /**
   * // String CRITERION_RECEIPIENT = "getReceipientUserIDStr"; 
   * // String CRITERION_SUBJECT ="getSubject";
   * // String CRITERION_MESSAGE = "getAttatchmentNum"; 
   * // String CRITERION_MESSAGE_BODY = "getMessgeContentString"; 
   * // String CRITERION_EMAILTO =   "getToEmailAddressAndUserIDGroupIDRoleID"; 
   * // String CRITERION_EMAILCC =  "getCCEmailAddressAndUserIDGroupIDRoleID"; 
   * // String CRITERION_EMAILFROM = "getSenderEmailAddressAndUserIDGroupIDRoleID";
   * 
   * @param name
   * @return
   */
  private String getEmailValue(String name) {
    String value = "";

    if ("getReceipientUserIDStr".equalsIgnoreCase(name.trim())) {
      value = this.messageInfoBean.getEmailTo() + "," + this.messageInfoBean.getEmailcc();
    }
    else if ("getSubject".equalsIgnoreCase(name.trim())) {
      value = this.messageInfoBean.getEmailSubject();
    }
    else if ("getAttatchmentNum".equalsIgnoreCase(name.trim())) {
      value = this.messageInfoBean.getAttatchmentNum();
    }
    else if ("getToEmailAddressAndUserIDGroupIDRoleID".equalsIgnoreCase(name.trim())) {
      value = this.messageInfoBean.getEmailTo();
    }
    else if ("getCCEmailAddressAndUserIDGroupIDRoleID".equalsIgnoreCase(name.trim())) {
      value =  this.messageInfoBean.getEmailcc();
    }
    else if ("getSenderEmailAddressAndUserIDGroupIDRoleID".equalsIgnoreCase(name.trim())) {
      value =  this.messageInfoBean.getEmailFrom();
    }
    else if ("getMessgeContentString".equalsIgnoreCase(name.trim())) {
      value = "";
    }
    return value;
  }

  /**
   * @param emailInfo
   * @return
   */
  private String[] getConditionName(String conditionName) {
    EmailRuleEngineHelper emailRuleEngineHelper = new EmailRuleEngineHelper();
    String[] oldNames = conditionName.split(",");
    String[] conditionNames = new String[oldNames.length];
    Hashtable conditionHt = (Hashtable) emailRuleEngineHelper.getConditionHashtable(this.sessionContainer.getSessionLocale());
    for (int i = 0; i < oldNames.length; i++) {
      if (conditionHt.containsKey(oldNames[i].trim())) {
        conditionNames[i] = (String) conditionHt.get(oldNames[i].trim());
      }
      else {
        conditionNames[i] = oldNames[i].trim();
      }
    }
    return conditionNames;
  }
  
  private String replacespecialChar(String inputStr) {
    String outStr = "";
    if (!Utility.isEmpty(inputStr)) {
      outStr = inputStr;
      if (inputStr.indexOf(RuleManager.REPLACESTR) != -1) {
        outStr = inputStr.replaceAll(RuleManager.REPLACESTR, ",");
      }
    }
    return outStr;
  }
  /**
   * @param emailInfo
   */
  private void makeRuleAction(String actionStr) {
    EmailRuleEngineHelper emailRuleEngineHelper = new EmailRuleEngineHelper();
    Hashtable actionHt= (Hashtable) emailRuleEngineHelper.getActionCategoryHashtable(this.sessionContainer.getSessionLocale());
    String[] actions = actionStr.split(",");
    List actionList=new ArrayList();
    for(int i=0;i<actions.length;i++){
      if(actionHt.containsKey(actions[i].trim())){
      actionList.add(actionHt.get(actions[i].trim()));
      }
    }
    this.messageInfoBean.setActionList(actionList);
  }


  private String replaceEspecialChar(String inputStr) {
    String outStr = "";
    if (!Utility.isEmpty(inputStr)) {
      outStr = inputStr;
      if (inputStr.indexOf(NotifyEmailArchiveAction.REPLACESTR) != -1) {
        outStr = inputStr.replaceAll(NotifyEmailArchiveAction.REPLACESTR, "\\|");
      }
    }
    return outStr;
  }

  private String[] makeEmailRuleInfo() {
    String message = this.alertSystemLog.getMessage();
    String[] emailInfo = message.split("\\|");
    return emailInfo;
  }

  
  /*private String makeEmailContent(String emailContent) {
    StringReader stringReader = new StringReader(emailContent);
    BufferedReader bufferReader = new BufferedReader(stringReader);
    StringWriter stringWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(stringWriter);
    String line="";
    try {
      while((line=bufferReader.readLine())!=null)
      {
        if(!line.trim().equals("")){
          while(line.length()>lineLength){
            writer.println(line.substring(0, lineLength));
            line=line.substring(lineLength);
          }
          writer.println(line);
        }
      }
    }
    catch (IOException e) {
      //don't to do anything;
    }
    return stringWriter.toString();
  }*/

}
